package com.five.monkey.feign.consumer.filter;

import com.five.monkey.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author 狻猊
 * @date 2021/8/10 下午7:14
 */
public class ConsumerInterceptor implements HandlerInterceptor {

    private static final Pattern pattern = Pattern.compile("^[1-9][0-9]*$");

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String cookieValue = null;
        if (Objects.isNull(cookies) || cookies.length <= 0) {
            response.sendError(CommonConstant.UNAUTHORIZED_CODE, "用户未登录,无用户cookie信息");
            return false;
        }
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), CommonConstant.COOKIE_NAME)) {
                cookieValue = cookie.getValue();
                break;
            }
        }
        if (StringUtils.isBlank(cookieValue)) {
            response.sendError(CommonConstant.UNAUTHORIZED_CODE, "用户未登录,无用户cookie信息");
            return false;
        }
        String[] strArr = StringUtils.split(cookieValue, CommonConstant.UNDERSCORE);
        if (strArr.length <= 0) {
            response.sendError(CommonConstant.UNAUTHORIZED_CODE, "无用户cookie信息");
            return false;
        }
        String userId = strArr[strArr.length - 1];
        if (!pattern.matcher(userId).matches()) {
            response.sendError(CommonConstant.UNAUTHORIZED_CODE, "用户cookie信息中无用户个人信息");
            return false;
        }
        request.setAttribute("userId", Long.parseLong(userId));
        return true;
    }
}
